package com.qiyou.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.qiyou.dao.IBlogCommentDao;
import com.qiyou.dao.factory.DaoFactory;
import com.qiyou.entity.BlogComment;
import com.qiyou.util.LogUtil;

/**
 * 回复博客评论服务
 * 
 * @author 杨强
 */
@WebServlet("/ReplyBlogService")
public class ReplyBlogService extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Logger log = LogUtil.getLogger(ReplyBlogService.class);

    public ReplyBlogService() {
        super();
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");

        String userID = request.getParameter("userID");
        String blogIDStr = request.getParameter("bolgID");
        String motherIDStr = request.getParameter("motherID");
        String content = request.getParameter("comment");

        BlogComment comment = new BlogComment();
        try {
            comment.setUserID(userID);
            comment.setBlogID(Long.parseLong(blogIDStr));
            comment.setMotherID(motherIDStr == null ? null : Long
                    .parseLong(motherIDStr));
            comment.setContent(content);
        } catch (NumberFormatException e) {
            log.error(e);
        }
        IBlogCommentDao dao = DaoFactory.getBlogCommentDao();

        boolean result = false;
        try {
            result = dao.doCreate(comment);
        } catch (SQLException e) {
            log.error(e);
        }

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
        String msg = gson.toJson(result);
        PrintWriter out = response.getWriter();
        out.print(msg);
        out.flush();
        out.close();

        log.info("用户:" + request.getRemoteAddr() + "博客:" + blogIDStr + "评论:"
                + motherIDStr + ",评论内容:" + content + ",评论结果:" + msg);
    }
}
